package cn.idietrade.idietradeesmodule9000.service.goodsservice.impl;

import cn.idietrade.common.pojo.SecondGoods;
import cn.idietrade.common.utils.EmptyUtils;
import cn.idietrade.common.utils.SecondPage;
import cn.idietrade.idietradeesmodule9000.service.feignservice.GoodsFeignService;
import cn.idietrade.idietradeesmodule9000.service.goodsservice.GoodsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author zjy
 * @version 1.0
 * @createTime 2022-12-03 17:42
 * @description
 */
@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsFeignService goodsFeignService;

    @Resource
    private RestHighLevelClient restHighLevelClient ;


    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    Logger logger =Logger.getLogger("GoodsServiceImpl");

    /*
    * 定时同步数据任务
    * 秒   分   时     日   月   周几 表示每个星期三凌晨3点 调用该方法同步数据
    * */


    @Scheduled(cron = "0 0 3 ? * WED")
    @Override
    public void goodsAddES() {
        List<SecondGoods> goodsList = goodsFeignService.queryGoodsAll(null,null);
        if(EmptyUtils.isNotEmpty(goodsList)){
            elasticsearchRestTemplate.save(goodsList);
            logger.info("数据同步成功");
        }else{
            logger.info("没有对应数据");
        }
    }


    @RabbitListener(queues = "syncQueue")
    @Override
    public void goodsAllAddES(String sengoods,String keword) {
        try {
            if(EmptyUtils.isNotEmpty(sengoods)){
                List<SecondGoods> goodsList = goodsFeignService.queryGoodsAll(null,null);
                if(EmptyUtils.isNotEmpty(goodsList)){
                    elasticsearchRestTemplate.save(goodsList);
                    logger.info("数据同步成功");
                }else{
                    logger.info("没有对应数据");
                }
            }else{
                List<SecondGoods> goodsList = goodsFeignService.queryGoodsAll(keword,null);
                if(EmptyUtils.isNotEmpty(goodsList)){
                    elasticsearchRestTemplate.save(goodsList);
                    logger.info("数据同步成功");
                }else{
                    logger.info("没有对应数据");
                }
            }
        }catch (Exception e){
            logger.info("同步数据程序异常");
            e.printStackTrace();
        }
    }



    @Override
    public SecondPage goodsShow(Integer pageNum, Integer pageSize, String keyword, Integer cityId, Integer goodsType) throws IOException {
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("idie_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //显示商品为审核通过的
        boolQuery.must(QueryBuilders.matchQuery("goodsState",0));
        if(EmptyUtils.isEmpty(keyword)){ //关键字为空查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("goodsName", keyword));
        }
        if(EmptyUtils.isNotEmpty(cityId)&&cityId>0){
            boolQuery.must(QueryBuilders.matchQuery("cityId",cityId));
        }
        if(EmptyUtils.isNotEmpty(goodsType)){
            boolQuery.must(QueryBuilders.matchQuery("goodsType",goodsType));
        }

        //分页
        int currentPage=(pageNum-1)*pageSize;
        searchSourceBuilder.from(currentPage);
        searchSourceBuilder.size(pageSize);
        //按照搜索权重排序
        searchSourceBuilder.sort("_score", SortOrder.DESC);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("goodsName"); //高亮的字段
        highlightBuilder.requireFieldMatch(false); //多个高亮 false关闭
        highlightBuilder.preTags("<span style='color: red;'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.query(boolQuery);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SecondPage secondPage =new SecondPage();
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        //总条数
        long value = searchResponse.getHits().getTotalHits().value;
        secondPage.setTotal((int) value);

        for (SearchHit hit : searchResponse.getHits().getHits()) {
            //获取高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField titles = highlightFields.get("goodsName");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果

            //解析高亮的字段 将原来的字段换为我们高亮的字段即可
            if(titles!=null){
                Text[] fragments = titles.fragments();
                String n_title="";
                for (Text fragment : fragments) {
                    n_title+=fragment;
                }
                sourceAsMap.put("goodsName",n_title);//替换高亮字段
            }
            list.add(sourceAsMap);
        }
        secondPage.setMapList(list);
        return secondPage;
    }


}

